const loadBus = (() => {
    let bus = [];
    const run = () => {
        let BUS = bus;
        bus = null;
        for (let i in BUS) {
            let func = BUS[i];
            try {
                func();
            } catch (err) {
                APP.error("Counter - 无法加载计数器", err);
            }
        }
    }
    const init = (func) => {
        if (bus) bus.push(func);
        else throw new Error('[Counter Init] Loading Bus has gone!');
    }
    init.run = run;
    return init;
})();

const HotCounter = (() => {
    let cache = {};
    let update = new Set();
    const add = catId => {
        if (isNaN(catId) && !cache[catId]) return false;
        catId = parseInt(catId);
        cache[catId]++;
        return update.add(catId);
    }
    add.flush = () => {
        if (update.size <= 0) return;
        let data = {};
        update.forEach(id => data[id] = cache[id]);
        update.clear();
        return dm.saveCatHot(data);
    }
    add.get = () => ({ ...cache });
    const load = async () => {
        let hot = await dm.getCatHot();
        for (let i in hot) cache[hot[i].id] = hot[i].val;
    }
    loadBus(load);
    setInterval(add.flush, 1000 * 60);
    return add;
})();

module.exports = {
    HotCounter: HotCounter,
}

const dm = require("../core/DataManager");
loadBus.run();